class BusinessProcess < ActiveRecord::Base
  belongs_to :business_process_class

  has_and_belongs_to_many :enter_resources, :class_name => "ObjectAndResourceClass",  :join_table => :enters
  has_and_belongs_to_many :exit_resources,  :class_name  => "ObjectAndResourceClass", :join_table => :exits
  
  DIRECTORY_WHOLE = 'images/diagram_whole'
  DIRECTORY_DECOMPOSED = 'images/diagram_decomposed'
  
  @@process_flag = true
  
  after_save :process
  after_destroy :cleanup
  
  def diagram_whole_file_data=(diagram_whole_file_data)
    @diagram_whole_file_data = diagram_whole_file_data
  end
  
  def diagram_decomposed_file_data=(diagram_decomposed_file_data)
    @diagram_decomposed_file_data = diagram_decomposed_file_data
  end
  
  def path_diagram_whole
    File.join(DIRECTORY_WHOLE, "#{self.id}-whole.svg")
  end
  
  def path_diagram_decomposed
    File.join(DIRECTORY_DECOMPOSED, "#{self.id}-decomposed.svg")
  end
  
  #----------
  
  private
  
  def process
    if @@process_flag == true
      @@process_flag = false   # Для того, чтобы программа не ушла в бесконечную рекурсию
      
      # Сохранть общую диграмму
      if @diagram_whole_file_data
        create_directory DIRECTORY_WHOLE   # Создать каталог для хранения целой диаграммы
        save_diagram_whole                 # Сохранить диаграмму
        update_attribute('diagram_whole', "#{self.id}-whole.svg")
      end
    
      # Сохранить декомпозированную диаграмму
      if @diagram_decomposed_file_data
        create_directory DIRECTORY_DECOMPOSED   # Создать каталог для хранения декомпозированной диаграммы
        save_diagram_decomposed                 # Сохранить диаграмму
        update_attribute('diagram_decomposed', "#{self.id}-decomposed.svg")
      end
    end
  end
  
  def cleanup
    Dir[File.join(DIRECTORY_WHOLE, "#{self.id}-*")].each do |filename|
      File.unlink(filename) rescue nil
    end
    
    Dir[File.join(DIRECTORY_DECOMPOSED, "#{self.id}-*")].each do |filename|
      File.unlink(filename) rescue nil
    end
  end
  
  def save_diagram_whole
    File.open(path_diagram_whole, 'wb') do |file|
      file.puts @diagram_whole_file_data
    end
  end
  
  def save_diagram_decomposed
    File.open(path_diagram_decomposed, 'wb') do |file|
      file.puts @diagram_decomposed_file_data
    end
  end
  
  def create_directory(dir_name)
    FileUtils.mkdir_p dir_name
  end
  
end
